/**
 * Project Name: tank_practice
 * File Name: Bullet
 * Package Name: com.hmz.tank
 * Date: 2020/7/26 14:56
 * Copyright (c) 2020,All Rights Reserved.
 */
package com.hmz.tank;

import java.awt.*;

public class Bullet {
    private int x,y;
    public static int WIDTH = ResourceMgr.bulletD.getWidth();
    public static int HEIGHT = ResourceMgr.bulletD.getHeight();
    private static final int SPEED = PropertyMgr.getIntValue("bulletSpeed");
    Rectangle rec = new Rectangle();

    private Dir dir;
    private boolean living = true;
    TankFrame tf = null;
    private Group group;


    public Bullet(int x, int y, Dir dir,Group group,TankFrame tf) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.group = group;
        this.tf = tf;

        // init rec
        rec.x = x;
        rec.y = y;
        rec.height = HEIGHT;
        rec.width = WIDTH;
    }

    public void paint(Graphics g) {
        if(!living) {
            tf.bullets.remove(this);
        }
        switch (dir) {
            case LEFT:
                g.drawImage(ResourceMgr.bulletL,x,y,null);
                break;
            case RIGHT:
                g.drawImage(ResourceMgr.bulletR,x,y,null);
                break;
            case UP:
                g.drawImage(ResourceMgr.bulletU,x,y,null);
                break;
            case DOWN:
                g.drawImage(ResourceMgr.bulletD,x,y,null);
                break;
        }
        move();
    }

    private void move() {
        switch (dir) {
            case UP:
                y -= SPEED;
                break;
            case DOWN:
                y += SPEED;
                break;
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
        }
        if(x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) {
            living = false;
        }

        // update rec
        rec.x = x;
        rec.y = y;
    }


    public void collideWith(Tank tank) {
        if (this.group == tank.getGroup()) {
            return;
        }
//        Rectangle bulletRec = new Rectangle(x,y,WIDTH,HEIGHT);
//        Rectangle tankRec = new Rectangle(tank.getX(),tank.getY(),Tank.WIDTH,Tank.HEIGHT);
        if(rec.intersects(tank.rec)) {
            tank.die();
            this.die();
            int eX = tank.getX() + Tank.WIDTH/2 - Explode.WIDTH/2;
            int eY = tank.getY() + Tank.HEIGHT/2 - Explode.HEIGHT/2;
            tf.explodes.add(new Explode(eX,eY,tf));
        }

    }

    private void die() {
        this.living = false;
    }
}
